import redis
import requests
from config import BasicInfo

BasicInfo = BasicInfo()
host = BasicInfo.host

def ClearIpPoor():
    re_queue = redis.Redis(host=host, port=6379)
    while True:
        result = re_queue.lpop("ips")
        if result == None:
            print('Clear Ip-Poor Success')
            break

def IPtest(IP):
    try:
        r = requests.get("http://www.baidu.com",proxies=IP,timeout=5)
        return True
    except:
        return False

def UpdataPorxy():
    re_queue = redis.Redis(host=host, port=6379)
    purl = BasicInfo.ThreeIpUrl
    ips = requests.get(purl).text.split("\n")
    for ip in ips[:-1]:
        proxy_dict = {
        "http": "http://"+ip,
        "https": "https://"+ip
        }
        re_queue.lpush("ips", proxy_dict)

def GetProxy():
    re_queue = redis.Redis(host=host, port=6379)
    result = re_queue.lpop("ips")
    if result==None:
        UpdataPorxy()
        return GetProxy()
    IP = eval(result.decode())
    if IPtest(IP):
        return IP
    else:
        return GetProxy()
